package com.chen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.common.Constants;
import com.chen.common.RoleEnum;
import com.chen.entity.User;
import com.chen.entity.Video;
import com.chen.entity.vo.UserDTO;
import com.chen.entity.vo.UserPasswordDTO;
import com.chen.exception.ServiceException;
import com.chen.mapper.UserMapper;
import com.chen.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Y·C
 * @since 2023-04-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {




    @Autowired
    private UserMapper userMapper;


    private static final Log LOG = Log.get();



    @Override
    public UserDTO login(UserDTO userDTO) {
        // 用户密码 md5加密
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        User one = getUserInfo(userDTO);
        if (!"ROLE_ADMIN".equals(one.getRole())){
            throw new ServiceException("2001","权限不足");
        }

        if (one != null) {
            //将one用户信息复制给userDTO
            BeanUtil.copyProperties(one, userDTO, true);
            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);

            return userDTO;

        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        // 用户密码 md5加密
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);
            // 默认后台注册默认admin角色
            one.setRole(RoleEnum.ROLE_ADMIN.toString());
            if (one.getUsername() == null) {
                one.setUsername(one.getUsername());
            }
            save(one);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }
    /**
     * 从数据库中查询用户信息
     * */
    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }


    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }


    @Override
    public void updatePasswordFront(UserPasswordDTO userPasswordDTO) {
      int updateFront = userMapper.updatePasswordFront(userPasswordDTO);
      if (updateFront<1){
          throw new ServiceException(Constants.CODE_600, "密码错误");
      }
    }

    @Override
    public UserDTO loginFront(UserDTO userDTO) {

        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));

        User one;
        if (userDTO.getUsername()!=null) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", userDTO.getUsername());
            wrapper.eq("password", userDTO.getPassword());
           one = getOne(wrapper);
        }else {
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("email",userDTO.getEmail());
        wrapper1.eq("password",userDTO.getPassword());
             one = getOne(wrapper1);
        }
        if (one.getState()==0){
            throw new ServiceException(Constants.CODE_600,"用户还在审核");
        }


        if (one != null ) {
            //将one用户信息复制给userDTO
            BeanUtil.copyProperties(one, userDTO, true);
            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        }else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }


    }


    @Override
    public User registerFront(UserDTO userDTO) {
        // 用户密码 md5加密
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));

        String email = userDTO.getEmail();
        String username = userDTO.getUsername();

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("email",email);

        User one = getOne(wrapper);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);
            // 默认后台注册默认admin角色
            one.setRole(RoleEnum.ROLE_USER.toString());
            if (one.getUsername() == null) {
                one.setUsername(one.getUsername());
            }
            save(one);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }


    //修改信息
    @Override
    public void manageInfo(User user) {
        int i = userMapper.updateById(user);
        if (i<1){
            throw new ServiceException(Constants.CODE_600, "修改失败");
        }
    }


    @Override
    public void adoptByCids(List<Integer> ids) {

        //批量修改
        User user = new User();
        user.setState(1);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.in("id", ids);
        baseMapper.update(user, wrapper);

    }

    @Override
    public Boolean lock(Integer id, Integer  state) {
        if ( state.intValue() == 0 ||  state.intValue() == 1) {
            User user = this.getById(id);
            user.setState(state);
            this.updateById(user);
            return true;
        }
        return false;
    }



}
